package benchmarks;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
import org.exolab.castor.xml.XMLContext;

import edu.vub.at.objects.natives.NATText;

public class CastorLib implements TestMethods {//TODO pokke traag /skip
	
	public Mapping map;
	public XMLContext context;
	
	public CastorLib() throws MappingException{
		map = new Mapping();
		context = new XMLContext();
		context.addMapping(map);
		context.createMappingTool().addClass(NATText.class);

	
	}
	@Override
	public byte[] serialize(Object o) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			context.createMarshaller().marshal(o, new OutputStreamWriter(out));
		} catch (MarshalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ValidationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return out.toByteArray();
	}

	@Override
	public Object deserialize(byte[] b, Class c) throws IOException,
			ClassNotFoundException {
		
		ByteArrayInputStream in = new ByteArrayInputStream(b);
		try {
			return context.createUnmarshaller().unmarshal(c, new InputStreamReader(in));
		} catch (MarshalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ValidationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return in;
	}

	@Override
	public Object copy(Object o) throws IOException, ClassNotFoundException {
		return deserialize(serialize(o), o.getClass());
	}

}
